import { ref, computed } from 'vue'

// 全局加载状态管理
const globalLoadingStates = ref(new Map())
const pageLoading = ref(false)
const requestCounter = ref(0)

/**
 * 加载状态管理组合式函数
 * 用于管理页面和组件的加载状态
 */
export function useLoading(namespace = 'default') {
  // 获取或创建命名空间的加载状态
  if (!globalLoadingStates.value.has(namespace)) {
    globalLoadingStates.value.set(namespace, {
      loading: ref(false),
      progress: ref(0),
      message: ref(''),
      error: ref(null)
    })
  }

  const state = globalLoadingStates.value.get(namespace)

  // 开始加载
  const startLoading = (message = '加载中...') => {
    state.loading.value = true
    state.message.value = message
    state.error.value = null
    state.progress.value = 0
  }

  // 停止加载
  const stopLoading = () => {
    state.loading.value = false
    state.message.value = ''
    state.progress.value = 100
  }

  // 设置加载进度
  const setProgress = (progress, message) => {
    state.progress.value = Math.max(0, Math.min(100, progress))
    if (message) {
      state.message.value = message
    }
  }

  // 设置错误
  const setError = (error) => {
    state.error.value = error
    state.loading.value = false
  }

  // 包装异步函数，自动管理加载状态
  const withLoading = async (asyncFn, message = '加载中...') => {
    try {
      startLoading(message)
      const result = await asyncFn()
      stopLoading()
      return result
    } catch (error) {
      setError(error)
      throw error
    }
  }

  // 带进度的异步操作
  const withProgress = async (asyncFn, options = {}) => {
    const {
      message = '处理中...',
      steps = [],
      onProgress = null
    } = options

    try {
      startLoading(message)

      if (steps.length > 0) {
        // 分步骤执行
        for (let i = 0; i < steps.length; i++) {
          const step = steps[i]
          const progress = ((i + 1) / steps.length) * 100

          setProgress(progress, step.message || message)

          if (onProgress) {
            onProgress(progress, step.message)
          }

          if (step.action) {
            await step.action()
          }

          // 模拟步骤间的延迟
          if (step.delay && i < steps.length - 1) {
            await new Promise(resolve => setTimeout(resolve, step.delay))
          }
        }
      } else {
        // 单个异步操作
        const result = await asyncFn((progress, msg) => {
          setProgress(progress, msg)
          if (onProgress) {
            onProgress(progress, msg)
          }
        })

        stopLoading()
        return result
      }

      stopLoading()
    } catch (error) {
      setError(error)
      throw error
    }
  }

  return {
    // 状态
    loading: computed(() => state.loading.value),
    progress: computed(() => state.progress.value),
    message: computed(() => state.message.value),
    error: computed(() => state.error.value),

    // 方法
    startLoading,
    stopLoading,
    setProgress,
    setError,
    withLoading,
    withProgress
  }
}

/**
 * 页面级加载状态管理
 */
export function usePageLoading() {
  const startPageLoading = () => {
    pageLoading.value = true
  }

  const stopPageLoading = () => {
    pageLoading.value = false
  }

  const withPageLoading = async (asyncFn) => {
    try {
      startPageLoading()
      const result = await asyncFn()
      stopPageLoading()
      return result
    } catch (error) {
      stopPageLoading()
      throw error
    }
  }

  return {
    pageLoading: computed(() => pageLoading.value),
    startPageLoading,
    stopPageLoading,
    withPageLoading
  }
}

/**
 * 请求加载状态管理
 */
export function useRequestLoading() {
  const incrementRequest = () => {
    requestCounter.value++
  }

  const decrementRequest = () => {
    requestCounter.value = Math.max(0, requestCounter.value - 1)
  }

  const withRequestLoading = async (asyncFn) => {
    try {
      incrementRequest()
      const result = await asyncFn()
      decrementRequest()
      return result
    } catch (error) {
      decrementRequest()
      throw error
    }
  }

  return {
    requestLoading: computed(() => requestCounter.value > 0),
    requestCount: computed(() => requestCounter.value),
    withRequestLoading
  }
}

/**
 * 组合多个加载状态
 */
export function useCombinedLoading(...namespaces) {
  const states = namespaces.map(ns => {
    const { loading } = useLoading(ns)
    return loading
  })

  const isLoading = computed(() => {
    return states.some(loading => loading.value)
  })

  return {
    isLoading
  }
}

/**
 * 模拟加载进度的工具函数
 */
export function simulateProgress(duration = 2000, onProgress = null) {
  return new Promise((resolve) => {
    let progress = 0
    const increment = 100 / (duration / 50) // 每50ms更新一次

    const timer = setInterval(() => {
      progress += increment + Math.random() * increment * 0.5 // 添加一些随机性
      progress = Math.min(progress, 99) // 不要达到100%

      if (onProgress) {
        onProgress(Math.round(progress))
      }

      if (progress >= 99) {
        clearInterval(timer)
        if (onProgress) {
          onProgress(100)
        }
        setTimeout(resolve, 100) // 稍微延迟完成
      }
    }, 50)
  })
}

/**
 * 创建延迟加载函数
 */
export function createDelayedLoader(delay = 300) {
  let timeoutId = null

  const startDelayedLoading = (callback) => {
    if (timeoutId) {
      clearTimeout(timeoutId)
    }

    timeoutId = setTimeout(callback, delay)
  }

  const cancelDelayedLoading = () => {
    if (timeoutId) {
      clearTimeout(timeoutId)
      timeoutId = null
    }
  }

  return {
    startDelayedLoading,
    cancelDelayedLoading
  }
}

// 导出一些常用的加载配置
export const loadingConfigs = {
  // 快速加载（用于简单操作）
  quick: {
    type: 'apple',
    text: '正在处理...'
  },

  // 数据加载
  data: {
    type: 'spinner',
    text: '正在加载数据...'
  },

  // 文件上传
  upload: {
    type: 'progress',
    text: '正在上传文件...'
  },

  // 页面切换
  page: {
    type: 'wave',
    text: '正在加载页面...'
  },

  // 搜索
  search: {
    type: 'pulse',
    text: '正在搜索...'
  }
}